﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetOpenAuth.OAuth2;
using FourSquareSharp.MVC.Code.FourSquare;

namespace FourSquareSharp.MVC.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {

            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public void Test()
        {
            var token = Session["OAuthSessionToken"].ToString();

            Response.Write("<hr noshade/>UsersSelf:<br/>");
            Response.Write(FourSquareApi.UsersSelf(token));

            Response.Write("<hr noshade/>UsersCheckins:<br/>");
            Response.Write(FourSquareApi.UsersCheckins(token));

            Response.Write("<hr noshade/>UsersTips:<br/>");
            Response.Write(FourSquareApi.UsersTips(token));

            Response.Write("<hr noshade/>UsersTodos:<br/>");
            Response.Write(FourSquareApi.UsersTodos(token));

            Response.Write("<hr noshade/>");
            Response.End();


        }


        public ActionResult Authorize()
        {
            var authorization = (AuthorizationState)(Session["AuthState"] ?? new AuthorizationState());

            var authServer = new DotNetOpenAuth.OAuth2.AuthorizationServerDescription()
            {
                AuthorizationEndpoint = (new Uri(ConfigurationManager.AppSettings["FourSquareAuthorizationEndpoint"])),
                ProtocolVersion = ProtocolVersion.V20,
                TokenEndpoint = new Uri(ConfigurationManager.AppSettings["FourSquareTokenEndpoint"])
            };

            var client = new DotNetOpenAuth.OAuth2.WebServerClient(authServer, ConfigurationManager.AppSettings["FourSquareClientId"], ConfigurationManager.AppSettings["FourSquareClientSecret"]);
                
            if(String.IsNullOrWhiteSpace(Request["code"]))
            {
                var webResponse = client.PrepareRequestUserAuthorization(authorization);
                webResponse.Send();
                return null;
            }
            else
            {
                var authState = client.ProcessUserAuthorization();
                Session.Add("OAuthSessionToken",authState.AccessToken);
                Session.Add("AuthState",authState);
                return RedirectToAction("Test");
            }
        }

        public ActionResult About()
        {
            return View();
        }
    }
}
